<template>
  <el-dialog v-model="open">
    <el-form :model="data.orgin">
      <el-form-item label="地址" prop="url">
        <el-input  v-model="data.orgin.url"  placeholder="请填写地址" clearable />
      </el-form-item>

      <el-form-item label="描述" prop="des">
        <el-input v-model="data.orgin.des"  placeholder="请填写描述" clearable />
      </el-form-item>

      <el-form-item label="图片上传" prop="pictureId">
      </el-form-item>
      <div class="image-container">
        <img v-if="data.imageUrl" :src="data.imageUrl" alt="粘贴的图片" />
        <p v-else>粘贴后，图片会显示在这里。</p>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="open = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
import type {DetailModeTipsForm, DetailModeTipsRow} from "@/api/types/detailmodel/detailModeTips";
import {uploadFile2} from "@/api/modules/system/upload";
import {createDetailModeTipsApi, getDetailModeTipsDetailApi} from "@/api/modules/detailModel/detailModeTips";
import {ElMessage} from "element-plus";

let open =ref(false)

let props = defineProps({
  masterId: Number
})

let data =reactive({
  masterId: props.masterId,
  imageUrl:'' as string | undefined,
  id: null  as any | undefined,
  blob: null  as any | undefined,
  orgin: {} as DetailModeTipsRow
})


let openTipDialog = (id: any)=>{
  if (id){
    getDetailModeTipsDetailApi( { id: id }).then( res=>{
      console.log('获得数据res',res)
      data.id = res?.data?.id
      data.imageUrl = res?.data?.pictureId
      Object.assign(data.orgin,res?.data)
      console.log('变更后的数据data',data)

    })
  }
  open.value =true;
}

let handleSubmit = ( )=>{
    if(data.imageUrl === ''){
      ElMessage.error('没有图片可上传')
      return
    }

    if(data.blob){
      const response = uploadFile2({uploadSelf: data.blob}).then(res =>{
        let form :DetailModeTipsForm ={}
        Object.assign(form, data.orgin)
        form.belongId =data.masterId
        form.pictureId =res?.data
        createDetailModeTipsApi(form)
        ElMessage.success('上传成功')
      });
    }
}



// 处理粘贴事件
const handlePaste = (event: any) => {
  const items = event.clipboardData.items;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    // 检查是否为图片
    if (item.type.indexOf('image') === 0) {
      data.blob = item.getAsFile();
      if (data.blob) {
        data.imageUrl = URL.createObjectURL(data.blob);
      }
    }
  }
};

// 监听粘贴事件
onMounted(() => {
  document.addEventListener('paste', handlePaste);
});

// 清除事件监听器
onBeforeUnmount(() => {
  document.removeEventListener('paste', handlePaste);
});


defineExpose({openTipDialog})
</script>

<style scoped lang="scss">


.image-container {
  text-align: center;
  padding: 20px;
}

img {
  max-width: 100%;
  max-height: 300px;
  margin-top: 20px;
}
</style>